package com.sumer.psychology.common.persistence.mongodb;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Singleton;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * mongodb的配置
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/29
 * Time: 14:51
 */
@Singleton
public class MongoApplication {
    private static Logger logger = LoggerFactory.getLogger(MongoApplication.class);

    private MongoClient mongoClient;
    private String dbName;

    public MongoApplication(String dbName) {
        this.dbName = dbName;
    }

    public MongoApplication(String host, int port, String userName, String password, String dbName) {
        this(dbName);

        try {
            if (StringUtils.isAnyBlank(userName, password)) {
                setMongoClient(new MongoClient(host, port));
                return;
            }

            MongoCredential mongoCredential = MongoCredential.createMongoCRCredential(
                    userName,
                    dbName,
                    password.toCharArray());

            setMongoClient(new MongoClient(new ServerAddress(host, port), Arrays.asList(mongoCredential)));
        } catch (UnknownHostException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

    public DB db() {
        return mongoClient().getDB(dbName());
    }

    private String dbName() {
        return dbName;
    }

    protected void setMongoClient(MongoClient mongoClient) {
        this.mongoClient = mongoClient;
    }

    protected MongoClient mongoClient() {
        return mongoClient;
    }
}
